package com.example.rabbit.send;

import com.example.rabbit.BeanUtils;
import com.example.rabbit.enums.DelayEnum;
import com.example.rabbit.enums.DirectEnum;
import com.example.rabbit.enums.FanoutEnum;
import com.example.rabbit.enums.TopicEnum;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class RabbitUtil {

    private static RabbitTemplate staticRabbitTemplate;

    @Autowired
    public void setStaticRabbitTemplate(RabbitTemplate rabbitTemplate) {
        staticRabbitTemplate = rabbitTemplate;
    }


    public static Exchange getExchange(Enum<?> e) {
        return BeanUtils.getBean(getExchangeName(e));
    }

    public static String getExchangeName(Enum<?> e) {
        if (e instanceof DelayEnum) {
            return DelayEnum.valueOf(e.name()).getExchange();
        } else if (e instanceof FanoutEnum) {
            return FanoutEnum.valueOf(e.name()).getExchange();
        } else if (e instanceof TopicEnum) {
            return TopicEnum.valueOf(e.name()).getExchange();
        } else if (e instanceof DirectEnum) {
            return DirectEnum.valueOf(e.name()).getExchange();
        }
        return "";
    }

    /**
     * 发送消息到对应交换机
     *
     * @param obj
     */
    public static void send2Exchange(Enum<?> e, Object obj) {
        staticRabbitTemplate.convertAndSend(getExchangeName(e), "", obj);
    }


    public static void send2Exchange(Enum<?> e, Object obj, CorrelationData correlationData) {
        staticRabbitTemplate.convertAndSend(getExchangeName(e), "", obj, correlationData);
    }


    /**
     * 发送消息到对应交换机
     *
     * @param obj
     */
    public static void send2Exchange(Enum<?> e, Object obj, String routingKey) {
        staticRabbitTemplate.convertAndSend(getExchangeName(e), routingKey, obj);
    }

}
